import React from 'react'
import { Row, Col, Form, Input, Card, Button, message, notification } from 'antd'
import axios from 'axios'
import { store } from '../store/store'

const FormItem = Form.Item;

class CommonComments extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      comments: ''
    }
  }

  componentDidMount() {
    const uniquekey = this.props.uniquekey
    store.getComments(uniquekey)
      .then(comments => {
        this.setState({
          comments
        })
      })
  }

  componentWillReceiveProps(nextProps) {
    const uniquekey = nextProps.uniquekey
    store.getComments(uniquekey)
      .then(comments => {
        this.setState({
          comments
        })
      })
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, formData) => {
      if (!err) {
        axios.post('http://newsapi.gugujiankong.com/Handler.ashx?action=comment&userid=' + localStorage.userId + '&uniquekey=' + this.props.uniquekey + '&commnet=' + formData.remark)
          .then(message.success('发表成功'))
      }
    })
  }

  addUserCollection = () => {
    axios.post('http://newsapi.gugujiankong.com/Handler.ashx?action=uc&userid=' + localStorage.userId + '&uniquekey=' + this.props.uniquekey)
      .then(notification['success']({ message: 'ReactNews提醒', description: '收藏文章成功' }))
  }

  render() {
    const { getFieldProps } = this.props.form;
    const { comments } = this.state;
    const commentList = comments.length ? (
      comments.map((item, index) => {
        return (
          <Card key={index} title={item.UserName} extra={<a href='#'>发布于 {item.datetime}</a>} style={{ marginTop: '10px' }}>
            {item.Comments}
          </Card>
        )
      })
    ) : (
        '没有任何评论'
      )

    return (
      <div className='comment'>
        <Row>
          <Col span={24}>
            <Form onSubmit={this.handleSubmit}>
              <FormItem label='你的评论'>
                <Input type='textarea' placeholder="请输入你的观点" {...getFieldProps('remark')} />
              </FormItem>
              <Button type='primary' htmlType='submit'>发表评论</Button>
              <Button type='primary' htmlType='button' onClick={this.addUserCollection} style={{ marginLeft: '20px' }}>收藏文章</Button>
            </Form>
            {commentList}
          </Col>
        </Row>
      </div>
    )
  }
}

export default CommonComments = Form.create()(CommonComments);